
import api from "../../../common/api";
import { setData } from "../../../models/transferData";
import p from "../../../utils/platform";
const cityMap = require('./../../../utils/city')

const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    loading: true,
    readed: false,
    selectedIdList: [],
    userId: "",
    search: {},
    cityName: app.globalData._wx_city,
    cityCode: '',
    area: '', //区域
    areaCode:'',
    filterDistrictOption: {
      label: '区域',
      id: 'district',
      range: [
        [{
          label: '区域',
          value: 'district',
        }]
      ]
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let t = this
    let houseType = options.houseType || "SALES";
    this.data.houseType = houseType;

    getApp().globalData.loginPromise.then(({ sessionUser }) => {
      t.setData({
        cityName: app.globalData._wx_city,
        cityCode: t.getCityCodeByName(app.globalData._wx_city)
      })
      this.data.userId = sessionUser.id;
      this.fetchHouse();
    });
  },

  onSearchChange(e) {
    this.data.search = e.detail || {}
    this.fetchHouse();
  },
  
  onFilterChange(e) {
    let filter = e.detail
    if (filter.target === 'district') {
      this.data.area = filter.result[0].value || '',
      this.data.areaCode = filter.result[0].code || ''
    }
    this.fetchHouse();
  },

  fetchHouse() {
    this.setData({
      selectedIdList: [],
      list: [],
      loading: true,
    });
    let com = this.selectComponent("#com-scroll-content");
    if (com) {
      com.fetchHouse(1, this.apiFetch.bind(this));
    }
  },

  apiFetch({ page, pageSize }) {
    this.setData({ loading: true });

    return new Promise((resolve, reject) => {
      let param = {
        userId: this.data.userId,
        // resblockNameKeyWord: this.data.resblockNameKeyWord,
        resblockName: this.data.search.type === 'name' ? this.data.search.value : '',
        keyWords: this.data.search.type === 'key' ? this.data.search.value : '',
        cityCode:this.data.area? this.data.cityCode:'',
        cityName:this.data.area? this.data.cityName: '',
        area: this.data.area,
        areaCode:this.data.area? this.data.areaCode:'',
        delegationType: this.data.houseType,
        pageNum: page,
        pageSize: pageSize,
      };

      api.queryAvailablePublishHousePageInfo(param, (res) => {
        let data = res.data;
        let content = data.content
        let result = {
          handleData: this.handleData.bind(this),
          content: {
            page: content.pageNum,
            rows: content.list,
            total: content.pages,
          },
        };

        resolve(result);
      });
    });
  },

  handleData(rows) {
    this.setData({
      list: this.data.list.concat(rows),
      loading: false,
    });
  },

  handleRead() {
    this.setData({
      readed: !this.data.readed,
    });
  },

  handleSelect({ detail }) {
    let { id, select } = detail;
    console.log({ id, select });
    if (select) {
      this.setData({
        selectedIdList: this.data.selectedIdList.concat(id),
      });
    } else {
      this.setData({
        selectedIdList: this.data.selectedIdList.filter((v) => v != id),
      });
    }
  },
 
  // 发布房源
  handlePublish() {
    // if (!this.data.selectedIdList.length || !this.data.readed) return
    if (!this.data.selectedIdList.length) return
    api.publishCooperationHouse(this.data.selectedIdList, ({data}) => {
      if (data.isSuccess) {
        setData('isRefreshCooperation', true)
        p.showModal({
          title: '发房成功',
          content: '合作房源已发布成功，请及时关注IM的合作咨询消息~',
          confirmText: "继续发布",
          cancelText: "查看房源",
        }).then(({confirm}) => {
          if (confirm) {
            p.navigateBack()
          } else {
            p.navigateBack({delta: 2})
          }
        })
      }
    })
  },

  getCityCodeByName(name) {
    if(!name) {
      return ''
    }
    let cityCode = ''
    cityMap.cityObjs.forEach(item => {
      if (item.city === name) {
        cityCode = item.code || ''
      }
    })
    return cityCode
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

});
